<template>
  <div class="book">
    <!--    功能区域-->
    <div style="margin: 10px 0">
      <el-button type="primary" @click="addBook">上架书籍</el-button>
      <el-popconfirm
        @confirm="BulkDeletion"
        confirm-button-text='好的'
        cancel-button-text='不用了'
        icon="el-icon-info"
        icon-color="red"
        title="删除后无法恢复！"
      >
        <el-button size="mini" type="danger" slot="reference">批量删除</el-button>
      </el-popconfirm>
    </div>


    <!--    搜索区域-->
    <div style="margin: 10px 0">
      <el-input
        style="width: 20%"
        placeholder="请输入关键字"
        prefix-icon="el-icon-search"
        clearable
        v-model="search">
      </el-input>

      <el-button type="primary" plain @click="searchBook">搜索</el-button>
    </div>


    <!--    内容区域-->
    <!--    stripe：添加斑马纹-->
    <el-table
      :data="tableData"

      stripe

      border
      style="min-width: calc(100vh - 350px)"
      @selection-change="handleSelectionChange">


      <!--      sortable：给日期一个排序按钮-->
      <!--      <el-table-column
              prop="id"
              label="ID">

            </el-table-column>-->


      <el-table-column
        type="selection"
        width="55">
      </el-table-column>

      <el-table-column
        label="序号"
        type="index">
      </el-table-column>

      <!--      动态加载封面图片-->
      <el-table-column
        label="封面">
        <template slot-scope="scope">
          <el-image
            style="width: 100px; height: 100px"
            :src="scope.row.cover"
            :preview-src-list="filterImg(scope.row.cover)"
          >
            <!--            解决放大查看问题-->
          </el-image>

        </template>

      </el-table-column>

      <el-table-column
        prop="bookName"
        label="书名">

      </el-table-column>

      <el-table-column
        prop="price"
        label="价格">

      </el-table-column>


      <el-table-column
        prop="author"
        label="作者">

      </el-table-column>

      <el-table-column
        prop="capacity"
        label="数量">

      </el-table-column>


      <el-table-column
        prop="pubDate"
        label="出版日期">
      </el-table-column>

      <el-table-column
        prop="dop"
        label="上架日期">
      </el-table-column>

      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.row)">编辑
          </el-button>

          <el-popconfirm
            @confirm="deleteBook(scope.row)"
            confirm-button-text='好的'
            cancel-button-text='不用了'
            icon="el-icon-info"
            icon-color="red"
            title="下架后无法恢复！"
          >
            <el-button size="mini" type="danger" slot="reference">下架</el-button>
          </el-popconfirm>

        </template>
      </el-table-column>

    </el-table>

    <div style="margin: 10px 0">

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>

    </div>


    <!--    新增用户的表单-->
    <el-dialog title="请输入书籍信息" :visible.sync="dialogVisible" width="30%">
      <el-form :rules="rules" ref="form" :model="form" label-width="120px">

        <el-form-item label="书名：" prop="bookName">
          <el-input v-model="form.bookName" style="width: 70%"></el-input>
        </el-form-item>


        <el-form-item label="价格：" prop="price">
          <el-input v-model.number="form.price" style="width: 70%"></el-input>
        </el-form-item>

        <el-form-item label="数量：" prop="capacity">
          <el-input-number placeholder="最大只能上架100本" style="width: 70%" v-model="form.capacity" controls-position="right"
                           @change="handleChange" :min="1" :max="100"></el-input-number>
        </el-form-item>

        <el-form-item label="作者：">
          <el-input v-model="form.author" style="width: 70%"></el-input>
        </el-form-item>


        <el-form-item label="封面：">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8888/files/upload"
            :on-success="uploadSuccess"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>

        </el-form-item>

        <el-form-item label="出版日期">
          <el-col :span="11">
            <el-date-picker value-format="yyyy-MM-dd" type="date" placeholder="选择日期" v-model="form.pubDate"
                            style="width: 200%;"></el-date-picker>
          </el-col>
        </el-form-item>


      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="save('form')">确 定</el-button>
  </span>
    </el-dialog>


  </div>
</template>

<script>
import request from "../unitls/request";

export default {
  name: "Book",
  //加载页面
  created() {
    this.load();
  },
  methods: {
    //当多选框发生改变时
    handleSelectionChange(val) {
      this.ids = val.map(value => value.id);
      console.log(this.ids);
      console.log(this.ids.length);
    },
    //提交多选框的删除（批量删除）
    BulkDeletion() {
      if (!this.ids.length) {
        this.$message.warning("请选择数据！")
        return
      }
      request.post("/api/book/bulkDeletion", this.ids).then(success => {
        if (success.code === '0') {
          this.$notify({
            title: '删除成功',
            message: '共 ' + this.ids.length + ' 条记录删除成功！',
            type: 'success'
          });
          this.load();
        } else {
          this.$notify({
            title: '删除失败',
            message: success.msg,
            type: 'error'
          });
        }
      })

    },
    //上传图片成功之后的回调，设置图片
    uploadSuccess(response) {
      this.form.cover = response.data;  //将下载地址保存到数据库
      this.imageUrl = response.data;  //将响应的下载地址动态显示在页面中
    },
    //表格中的缩略图放大查看
    filterImg(item) {
      if (item) {
        //判断是否是集合类型
        return typeof item === "string" ? item.split("|") : item;
        /*if (typeof item === "string") {
          return item.split("|");
        } else {
          return item
        }*/
      }

    },
    //上架书籍
    addBook() {
      this.dialogVisible = true;

      //打开则清空表单
      this.form = {};
      this.imageUrl = '';//打开新增页面将已经上传的图片清空
    },

    //选择书籍数量时触发函数
    handleChange(value) {
      value === undefined ? 1 : value;
    },
    //搜索关键字
    searchBook() {
      this.load();

    },
    //编辑
    handleEdit(row) {
      //将传过来的row深拷贝给form
      this.form = JSON.parse(JSON.stringify(row));
      this.imageUrl = this.form.cover;//点击编辑将图片地址赋予
      this.dialogVisible = true;
    },
    //删除下架
    deleteBook(row) {
      // this.form = JSON.parse(JSON.stringify(row));
      request.delete("/api/book", {
        params: {
          id: row.id
        }
      }).then(success => {
          this.load();
          if (success.code === '0') {
            this.$notify({
              title: '下架成功',
              message: row.bookName + '下架成功！',
              type: 'success'

            });
          } else {
            this.$notify({
              title: '下架失败',
              message: success.msg,
              type: 'error'

            });
          }
        }
      )
    },

    //提交上架书籍信息
    save() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.form.id) {
            request.put("/api/book", this.form).then(success => {
              this.load();
              this.dialogVisible = false;
              if (success.code === '0') {
                this.$notify({
                  title: '更新成功',
                  message: success.data + '更新成功！',
                  type: 'success'

                });
              } else {
                this.$notify({
                  title: '更新失败',
                  message: success.msg,
                  type: 'error'

                });
              }

            })
          } else {
            request.post("/api/book", this.form).then(success => {
              this.load();
              this.dialogVisible = false;
              console.log(success);
              if (success.code === '0') {
                this.$notify({
                  title: '插入成功',
                  message: success.data + '插入成功！',
                  type: 'success'
                });
              } else {
                this.$notify({
                  title: '插入失败',
                  message: success.msg,
                  type: 'error'

                });
              }
            })
          }
        } else {
          console.log(this.form.pubDate)
        }

      })
    },
    //改变当前页的数据个数
    handleSizeChange(val) {
      this.pageSize = val
      this.load();
    },

    //改变当前页的页码
    handleCurrentChange(val) {
      this.currentPage = val;
      this.load();
    },

    //查询数据
    load() {
      request.get("/api/book", {

        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          searchStr: this.search
        }

      }).then(success => {

        this.tableData = success.data.records;
        this.total = success.data.total;
      })
    },
  },
  data() {
    //验证价格
    let checkPrice = (rule, value, callback) => {
      /*  if (!value) {
          return callback(new Error('价格不能为空'));
        }*/
      setTimeout(string => {
        if (!Number.isInteger(value)) {
          console.log(typeof value);
          console.log(value);

          callback(new Error('请输入数字值'));
        } else {
          if (value > 599 || value < 10) {
            callback(new Error('价格必须在 10 到 599 之间'));
          } else {
            callback();
          }
        }
      }, 100);
    };
    return {
      //多选框选中后拿到的值
      ids: [],
      //定义上传图片的地址
      imageUrl: '',
      //form 新增数据的表单
      form: {},
      //表单是否打开
      dialogVisible: false,
      //搜索
      search: '',
      //当前页
      currentPage: 1,
      //一页有多少条数据
      pageSize: 10,
      //数据总数
      total: 0,
      //后端传过来的数据
      tableData: [],
      //定义规则
      rules: {
        bookName: [
          {required: true, message: '请输入书名', trigger: 'blur'},
          {min: 1, max: 11, message: '长度在 1 到 11 个字符', trigger: 'blur'}
        ],
        price: [
          {required: true, message: '请输入价格', trigger: 'blur'},
          {validator: checkPrice, trigger: 'blur'}
        ],
        capacity: [
          {required: true, message: '请输入数量', trigger: 'blur'},
        ]
      }
    }
  }
}
</script>

<style scoped>
.book {
  padding: 10px;
  width: 800px;
}

.avatar-uploader {
  width: 178px;
  height: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
